use crate::{api::prelude::*, utils};
use axum::{body::Body, extract::State, http::header, response::IntoResponse};
use carpet::base::param::{Multipart, StreamResult};
use template_api::api::demo::file::*;

#[derive(Handler)]
pub struct FileHandler {
    pub db: State<String>,
}

#[impl_handler(HandleDef_)]
impl FileHandler {
    async fn _handle(self, Multipart(data): Multipart<RequestData>) -> StreamResult {
        info!("{:?}", data.description);
        let content_type = data
            .image
            .content_type
            .unwrap_or("application/octet-stream".into());
        let len_string = data.image.content.bytes.len().to_string();
        let body: Body = Body::from(data.image.content.bytes);
        let name = utils::urlencode(data.image.file_name.unwrap_or("noname".into()).as_str());
        let content_disposition = format!("attachment; filename=\"{}\"", &name);
        let headers = [
            (header::CACHE_CONTROL, "no-cache"),
            (header::CONTENT_LENGTH, len_string.as_str()),
            (header::CONTENT_TYPE, content_type.as_str()),
            (header::CONTENT_DISPOSITION, &content_disposition),
            (
                header::HeaderName::from_lowercase(b"x-filename").unwrap(),
                &name,
            ),
        ];
        let response = (headers, body).into_response();
        StreamResult {
            response: Box::new(response),
        }
    }
}
